import React, { Component } from "react";
import { View, Text, TextInput, TouchableOpacity } from "react-native";
import NavBarConfig from "../modules/NavBar";
import http from "../../util/http";
import { INVITE, INVITE_CODE, COUNTRY } from "../../config/Api";
import { toast } from "../../util/tip";
import { getTimer } from "../../util/util";
import TelSelect from "../modules/TelSelect";
import inviteStyles from "../../style/pages/InviteFriend";
import { Color } from "../../style/common";

class InviteFriend extends Component {
  static navigationOptions = ({ navigation }) =>
    NavBarConfig(
      {
        headerTitle: "邀請好友",
        headerRight: []
      },
      navigation
    );
  state = {
    tel: "",
    code: "",
    verifyMsg: "獲取驗證碼",
    countries: [],
    countryCode: "86",

    isCodeRequesting: false,
    isInviteRequesting: false
  };

  async getCountries() {
    const data = await http.get(COUNTRY);
    this.setState({
      countries: data.data
    });
  }

  componentWillMount() {
    this.getCountries();
  }

  handleCodeChange(country) {
    this.setState({
      contryCode: country.code
    });
  }

  handleChange(key, text) {
    let data = {};
    data[key] = text;
    this.setState({
      ...data
    });
  }

  async getInviteCode() {
    if (this.state.isCodeRequesting) return;
    await this.setState({
      isCodeRequesting: true
    });
    let value = this.state.tel.trim();
    if (value) {
      const countryData = this.state.countries.find(
        item => item.code == this.state.countryCode
      );


      const data = await http.post(INVITE_CODE, {
        tel: this.state.countryCode + value + "",
        country: countryData.shortname
      });

      if (data) {
        getTimer(
          50,
          time => {
            this.setState({
              verifyMsg: `${time}s`
            });
          },
          () => {
            this.setState({
              verifyMsg: "獲取驗證碼"
            });
          }
        );
      }
    } else {
      toast("請填寫正確的手機號");
    }
    this.setState({
      isCodeRequesting: false
    });
  }

  async handleInviteFriend() {
  
    if (this.state.isInviteRequesting) return;
    const tel = this.state.tel.trim();
    const code = this.state.code.trim();
    if (!code) {
      toast("請填寫正確的驗證碼");
      return;
    }
    this.setState({
      isInviteRequesting: true
    });
    try {
    const data = await http.post(INVITE, {
      tel: this.state.countryCode + tel,
      code: code
    });

    if (data) {
      toast("邀請成功");
      this.props.navigation.goBack();
    }
    this.setState({
      isInviteRequesting: false
    });
  } catch(e) {
    toast(e.message)
  }
  }

  render() {
    return (
      <View>
        <View style={inviteStyles.inviteFriendContainer}>
          <View style={inviteStyles.inviteFriendWrap}>
            <View>
              <TelSelect
                data={this.state.countries}
                onSelect={this.handleCodeChange.bind(this)}
              />
            </View>
            <TextInput
            underlineColorAndroid="transparent"
              style={inviteStyles.input}
              placeholder="請輸入好友手機號碼"
              onChangeText={text => this.handleChange("tel", text)}
            />
          </View>

          <View style={inviteStyles.inviteFriendWrap}>
            <TextInput
            underlineColorAndroid="transparent"
              style={inviteStyles.input}
              placeholder="請輸入短信驗證碼"
              onChangeText={text => this.handleChange("code", text)}
            />
            <TouchableOpacity
              style={[
                inviteStyles.buttonContain,
                this.state.isCodeRequesting ||
                this.state.verifyMsg !== "獲取驗證碼"
                  ? {
                      backgroundColor: "gray"
                    }
                  : {
                      backgroundColor: Color
                    }
              ]}
              disabled={
                this.state.isCodeRequesting ||
                this.state.verifyMsg !== "獲取驗證碼"
              }
              onPress={this.getInviteCode.bind(this)}
            >
              <Text style={inviteStyles.button}>{this.state.verifyMsg}</Text>
            </TouchableOpacity>
          </View>

          <Text style={inviteStyles.inviteTip}>
            邀請好友成功，雙方都可獲得一定的額度獎勵唷～
          </Text>
          <TouchableOpacity onPress={this.handleInviteFriend.bind(this)}>
            <Text style={inviteStyles.confirmButton}>確定</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

export default InviteFriend;
